$(function () {
    // 需求1: 初始化文章分类列表 - 封装成函数
    let layer = layui.layer;
    let form = layui.form
    initArtCateList();

    function initArtCateList() {
        axios({
            url: "/my/article/cates"
        }).then(({
            data: res
        }) => {
            console.log(res);
            if (res.status !== 0) {
                return layer.msg(res.message)
            }
            let arr = [`"<option value="">请选择文章类别</option>"`];
            res.data.forEach(ele => {
                if (ele.Id < 0) return;
                arr.push(` <option value="${ele.Id}">${ele.name}</option>`)
            });
            console.log(arr);
            let str = arr.join('')
            $("[name=cate_id]").empty().html(str);
            form.render();
        });

    }

    initEditor();
    // 需求三文章内容封面
    // 1. 初始化图片裁剪器
    var img = $('#image')

    // 2. 裁剪选项
    var options = {
        aspectRatio: 400 / 280,
        preview: '.img-preview'
    }

    // 3. 初始化裁剪区域
    img.cropper(options)

    // 需求四定义状态
    let state = ""
    $("#btn1").on("click", function () {
        state = "已发布"
    });
    $("#btn2").on("click", function () {
        state = "草稿"
    });

    $("#formPub").on("submit", function (e) {
        e.preventDefault();
        let fd = new FormData(this);
        fd.append("state", state)
        img
        .cropper("getCroppedCanvas",{
            width:400,
            height:280
        })
        .toBlob(function(blob){
            fd.append("cover_img",blob);
            console.log(...fd);
            // 发送ajax
            axios({
                method:'POST',
                url:"/my/article/add",
                data:fd
            }
                
            ).then(({data:res})=>{
              if (res.status!==0) {
                  return layer.msg(res.message)
              }
              layer.msg("恭喜你,添加文章成功!")
              setTimeout(function(){
                  window.parent.document.querySelector("#art_list").click();

              },1000)
            })





        })
    })
    // 需求5选择图片渲染图片
    $("#chooseImageBtn").on("click", function () {
        $("#chooseImageInp").click();

    });
    $("#chooseImageInp").on("change", function (e) {
        var file = e.target.files[0]
        if (file == undefined) {
            return layer.msg("文章封面不能为空!")
        }
        var newImgURL = URL.createObjectURL(file)
        img
            .cropper("destroy")
            .attr("src", newImgURL)
            .cropper(options)
    })
})